<?php

    /**
     * Returns array('success'=>true) or array('error'=>'error message')
     */
    function handleUpload() {
        session_name('czego_tu_szukasz');
        session_start();
        //$filename = $_FILES['qqfile']['tmp_name'];
        

        //$handle = fopen("php://input", "r");
        //$data = fread($handle, getSize());

        $data = file_get_contents("php://input");

        //$data = $_FILES['file'];

        //$data is file data
        $pvars   = array('image' => base64_encode($data), 'key' => '9aa7c9e87dffeeaf8decce12efd51832');
        $timeout = 30;
        $curl    = curl_init();

        curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.json');
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);

        $json = curl_exec($curl);

        curl_close ($curl);

        $decoded = json_decode($json);
        

        include_once 'Db.class.php';

        $db = new Db('../db/baza.sqlite3');
        //database add
           $qry = "INSERT INTO images (to_post, filename, uploaded_by) VALUES (:to_post, :filename, :uploaded_by)";
           $arr = array(
               ':to_post' => $_SESSION['uniqid'],
               ':filename' => $decoded->upload->image->hash,
               ':uploaded_by' => $_SESSION['user']['id']
           );
           $db->exec($qry, $arr);

        return array('success' => true);
    }
    
    




// to pass data through iframe you will need to encode all html tags
echo json_encode(handleUpload());
